﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;

namespace Swaf
{
	public class AssRez
	{
		protected static AssRez s_assRez = new AssRez();
		protected Dictionary<string, AssResource> m_resources = new Dictionary<string, AssResource>();
		protected Dictionary<string, Assembly> m_rezAssemblies = new Dictionary<string, Assembly>();

		public static AssRez Instance { get { return s_assRez; } }

		public class AssResource
		{
			public string RezName;
			public string AssName;
			public AssResource(string rezName, string assName)
			{
				RezName = rezName;
				AssName = assName;
			}
		}

		public void addAssembly(string assName)
		{
			addAssembly(assName, 0);
		}
		public void addAssembly(string assName, int stripDepth)
		{
			Assembly a = Cmn.findAssembly(assName);
			if (a != null)
				addAssembly(a, stripDepth);
		}

		public void addAssembly(Assembly ass)
		{
			addAssembly(ass, 0);
		}
		public void addAssembly(Assembly ass, int stripDepth)
		{
			string assName = ass.FullName;
			if(Application.currentApp != null)
				Application.currentApp.Log.println(Application.VERBOSE_STARTUP_LOG_LEVEL, "Loading resources from assembly {0}", assName);
			if (!m_rezAssemblies.ContainsKey(assName))
			{
				m_rezAssemblies[assName] = ass;
				string[] rezs = ass.GetManifestResourceNames();
				if (Application.currentApp != null)
					Application.currentApp.Log.println(Application.VERBOSE_STARTUP_LOG_LEVEL, "Found {0} resources in assembly {1}", rezs.Length, assName);
				foreach (string rez in rezs)
				{
					string rezName = rez;
					if (stripDepth > 0)
					{
						int c = 0;
						for(int pos = 0; pos < rez.Length; pos++)
							if (rez[pos] == '.' && ++c == stripDepth)
							{
								rezName = rez.Substring(pos + 1);
								break;
							}
					}
					m_resources.Add(rezName, new AssResource(rez, assName));
				}
			}
		}

		public bool rezExist(string name)
		{
			return m_resources.ContainsKey(name);
		}

		public Stream getResource(string name)
		{
			Stream str = null;
			AssResource assemblyName = null;
			if (m_resources.TryGetValue(name, out assemblyName))
			{
				Assembly ass = null;
				if (!m_rezAssemblies.TryGetValue(assemblyName.AssName, out ass))
				{
					ass = Assembly.LoadFrom(assemblyName.AssName);
					m_rezAssemblies.Add(assemblyName.AssName, ass);
				}
				if (ass != null)
					str = ass.GetManifestResourceStream(assemblyName.RezName);
			}
			return str;
		}

		public string getRezString(string name)
		{
			using (TextReader r = new StreamReader(getResource(name)))
			{
				return r.ReadToEnd();
			}
		}



		public Dictionary<string, AssResource>.KeyCollection KnownResourceNames
		{
			get { return m_resources.Keys; }
		}
	}
}
